package com.handong.handserialprogram.module.createmission.searchring;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.handong.handserialprogram.R;
import com.handong.handserialprogram.constants.KeyConstant;
import com.handong.handserialprogram.model.entities.FootRingNewEntity;
import com.handong.handserialprogram.model.entities.PersonEntity;
import com.handong.handserialprogram.model.entities.UploadTaskEntity;
import com.handong.handserialprogram.module.base.BackStackFragment;
import com.handong.handserialprogram.module.base.BaseView;
import com.handong.handserialprogram.module.createmission.CreateMissionActivity;
import com.handong.handserialprogram.module.singletask.MissionActivity;
import com.handong.handserialprogram.threadpool.FindRingsThread;
import com.handong.handserialprogram.ui.radar.RadarScanView;
import com.handong.handserialprogram.utils.AppUtil;
import com.handong.handserialprogram.utils.FootRingNewUtil;
import com.handong.handserialprogram.utils.SPUtil;
import com.handong.handserialprogram.utils.UserGuideUtil;
import com.handong.handserialprogram.utils.ViewUtil;
import com.handong.handserialprogram.widget.guideview.Guide;
import com.handong.handserialprogram.widget.guideview.GuideBuilder;

import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 快捷模式
 * SearchRingFragment：选择可用脚环。
 */
public class SearchRingFragment extends BackStackFragment<SearchRingPresenter> implements BaseView {

    private static final String TAG = SearchRingFragment.class.getSimpleName();

    private RadarScanView mRadarScanView;
    private RecyclerView mRingRecycler;

    private SearchRingAdapter mRingAdapter;
    private Guide mGuideInstance;


    //private Vector<FootRingNewEntity> mRingList;
    public String mMissionName, mMissionCar, mMissionTime;
    public UploadTaskEntity mUploadTaskEntity;


    public SearchRingFragment() {
    }

    public static SearchRingFragment newInstance(UploadTaskEntity uploadTaskEntity, Bundle bundle) {
        SearchRingFragment fragment = new SearchRingFragment();
        fragment.mUploadTaskEntity = uploadTaskEntity;
        fragment.mMissionName = bundle.getString(KeyConstant.MISSION_NAME);
        fragment.mMissionTime = bundle.getString(KeyConstant.MISSION_TIME);
        fragment.mMissionCar = bundle.getString(KeyConstant.MISSION_CAR);

        return fragment;
    }

    @Override
    protected int getContentViewID() {
        return R.layout.fragment_search_ring;
    }

    @Override
    protected SearchRingPresenter createPresenter() {
        return new SearchRingPresenter( this);
    }

    @Override
    protected void initViewByID(View view) {
        mRadarScanView = (RadarScanView) view.findViewById(R.id.searchRingRadarScan);
        mRingRecycler = (RecyclerView) view.findViewById(R.id.searchRingRecycler);
        mPresenter.scanAroundFootRing();
        mRadarScanView.startAnimation();
        CreateMissionActivity activity = (CreateMissionActivity) getActivity();
        if (activity.getmRingList().size() > 0) {
            showFootRingList(activity.getmRingList());
        }
    }

    @Override
    protected void initViewData() {

        initHeaderLayout("快捷查找脚环", "完成");
    }
    @Override
    public void onStart() {
        super.onStart();

    }

    @Override
    public void onStop() {
        super.onStop();
    }

    private String checkErrorFootring() {
        CopyOnWriteArrayList<FootRingNewEntity> mRingList = new CopyOnWriteArrayList<FootRingNewEntity>();
        StringBuilder result = new StringBuilder();
        CreateMissionActivity activity = (CreateMissionActivity) getActivity();
        //activity.mSerialPortUtil.SetReadRunnableIsStop(true);//首先停止recycle
        //String[] bindErrorFoot=new String[activity.getmRingList().size()];
        byte j = 0;
        for (int i = 0; i < activity.getmRingList().size(); i++) {
            FootRingNewEntity entity = activity.getmRingList().get(i);
            if (entity.isMyBingding()) {

                entity.setUwbCycle(j);
                entity.setIsActive(32);
                j++;
                for (int z = 0; z < 2; z++) {
                    activity.mSerialPortUtil.sendFootRing(entity);
//                entity.setReceiveData(false);
                    activity.mSerialPortUtil.mReadRunnable.ringId = entity.getRingID();
                    long startTime = System.currentTimeMillis();
                    while (!activity.mSerialPortUtil.mReadRunnable.DoWork(entity.getRingID(), false)) {
                        try {
                            Thread.sleep(1);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (System.currentTimeMillis() - startTime >= 500) {
                            activity.mSerialPortUtil.mReadRunnable.DoWork(entity.getRingID(), true);
                            //isReceive=false;
                            break;
                        }
                    }
                    if (entity.isReceiveData()) {
                        break;
                    }
                }
                if (!entity.isReceiveData()) {
                    //没有收到数据
                    if (!result.toString().equals("")) {
                        result.append(",");
                    }
                    result.append(entity.getRingID());

                } else {
                    mRingList.add(entity);
                }
                //showActivateGuideView(mRingAdapter.getView(i));
                //return;
            } else {
                mRingList.add(entity);
            }

        }
        if (!result.toString().equals("")) {
            activity.mSerialPortUtil.mReadRunnable.ringId = "";
            FootRingNewEntity entity = new FootRingNewEntity();
            entity.setPhoneSend(false);
            entity.setIsActive(0);
//            activity.mSerialPortUtil.sendFootRing(entity);
//            activity.mSerialPortUtil.setRingList(mRingList);
            activity.setmRingList(mRingList);
            showFootRingList(activity.getmRingList());
//            activity.mSerialPortUtil.SetReadRunnableIsStop(false);//恢复recycle
        }

        return result.toString();
    }

    @Override
    public void onClick(View v) {
        if (dispatchDoubleClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.headerOptionLayout://完成

                CreateMissionActivity activity = (CreateMissionActivity) getActivity();

                if (activity.getmRingList() == null || activity.getmRingList().isEmpty()) {
                    AppUtil.showLengthToast(getActivity(), "未查找到可使用的脚环");
                    return;
                }

                boolean isBindingAnyRing=FootRingNewUtil.checkListMyBingding(activity.getmRingList());
                if(!isBindingAnyRing){
                    AppUtil.showLengthToast(getActivity(),"请选择脚环");
                    return;
                }

                showRingSureDialog();//创建任务弹框

                break;
            default:
                super.onClick(v);
        }
    }


    /**
     * 显示脚环列表
     */
    protected void showFootRingList(CopyOnWriteArrayList<FootRingNewEntity> list) {
        CreateMissionActivity activity = (CreateMissionActivity) getActivity();

        if (!activity.getmRingList().isEmpty()) {
            if (mRadarScanView.isShown()) {
                mRadarScanView.stopAnimation();
                mRadarScanView.setVisibility(View.GONE);
                mRingRecycler.setVisibility(View.VISIBLE);
            }
        } else {
            if (!mRadarScanView.isShown()) {
                mRadarScanView.startAnimation();
                mRadarScanView.setVisibility(View.VISIBLE);
            }
            mRingRecycler.setVisibility(View.GONE);
        }


        if (mRingAdapter == null) {
            mRingAdapter = new SearchRingAdapter(mUploadTaskEntity.getCriminal(), activity.getmRingList(), this );
            mRingRecycler.setLayoutManager(new LinearLayoutManager(this.getContext().getApplicationContext()));
            mRingRecycler.setAdapter(mRingAdapter);
            ViewUtil.closeDefaultAnimator(mRingRecycler);
        } else {
            mRingAdapter.SetRingList(activity.getmRingList());
            mRingAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 激活脚环
     */
    protected void activateFootRing(String id) {
        mPresenter.activateFootRing(id);
    }

    /**
     * 脚环激活失败
     */
    protected void activateRingError(final String id) {
        dismissLoadingDialog();
        ViewUtil.removeHomeKeyListener(new MaterialDialog.Builder(getContext())
                .content("激活脚环失败，是否重试？")
                .negativeText(R.string.dialog_negative_text)
                .negativeColorRes(R.color.dialog_bg)
                .positiveText(R.string.dialog_positive_again)
                .positiveColorRes(R.color.back_ground_green)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog paramAnonymousMaterialDialog, @NonNull DialogAction paramAnonymousDialogAction) {
                        mPresenter.activateFootRing(id);
                    }
                }).build());
    }

    /**
     * 脚环激活成功
     */
    protected void activateRingSuccess() {
        dismissLoadingDialog();
        AppUtil.showShortToast(getContext(), "脚环已激活");
    }

    /**
     * 休眠成功
     */
    protected void logoutSuccess(String paramString) {

    }

    /**
     * 退出失败
     */
    protected void logoutFail(final String paramString) {
        ViewUtil.removeHomeKeyListener(new MaterialDialog.Builder(getContext())
                .content("休眠脚环失败")
                .negativeColorRes(R.color.dialog_bg)
                .positiveText("休眠")
                .positiveColorRes(R.color.back_ground_green)
                .negativeText("直接退出")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog paramAnonymousMaterialDialog, @NonNull DialogAction paramAnonymousDialogAction) {
                        mPresenter.logoutFootRing(paramString);
                    }
                }).onNegative(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog paramAnonymousMaterialDialog, @NonNull DialogAction paramAnonymousDialogAction) {
                        mPresenter.forceExit(paramString);
                        removeFrag(SearchRingFragment.this);
                    }
                }).build());
    }

    /**
     * 休眠脚环弹框
     */
    protected void showExitDialog(final String paramString) {
        ViewUtil.removeHomeKeyListener(new MaterialDialog.Builder(getContext())
                .content("是否休眠" + paramString + "脚环？")
                .negativeColorRes(R.color.dialog_bg)
                .positiveText("休眠")
                .positiveColorRes(R.color.back_ground_green)
                .negativeText(R.string.dialog_negative_text)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog paramAnonymousMaterialDialog, @NonNull DialogAction paramAnonymousDialogAction) {
                        mPresenter.logoutFootRing(paramString);

                    }
                }).build());
    }

    /**
     * 休眠全部脚环弹框
     */
    protected void showExitAllDialog() {
        ViewUtil.removeHomeKeyListener(new MaterialDialog.Builder(getContext())
                .content("退出前请先休眠脚环!")
                .negativeColorRes(R.color.dialog_bg)
                .positiveText("休眠")
                .positiveColorRes(R.color.back_ground_green)
                .negativeText(R.string.dialog_negative_text)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog paramAnonymousMaterialDialog, @NonNull DialogAction paramAnonymousDialogAction) {
                        mPresenter.logoutAllFootRing();

                    }
                }).build());
    }

    /**
     * sim错误
     */
    protected void simInitError(final String missID) {
        ViewUtil.removeAllKeyListener(new MaterialDialog.Builder(getActivity())
                .title(R.string.dialog_title_problem)
                .content("脚环:" + missID + " 获取Sim卡信息失败\n\n请注销重新检查！")
                .positiveText(R.string.dialog_positive_sleep)
                .canceledOnTouchOutside(false)
                .positiveColorRes(R.color.back_ground_green)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction dialogAction) {
                        mPresenter.logoutFootRing(missID);
                    }
                }).build());
    }

    @Override
    protected boolean onBackClicked() {
        CreateMissionActivity activity = (CreateMissionActivity) getContext();
        activity.IsFinish = true;
        for (FootRingNewEntity entity :
                activity.getmRingList()) {
            entity.setCriminalName("");
            entity.setCriminalId("");
        }
        for (PersonEntity personEntity : mUploadTaskEntity.getCriminal()) {
            personEntity.setSelected(false);
        }

        if (mGuideInstance != null) {
            mGuideInstance.dismiss();
            return true;
        }

//        if (!mPresenter.isCanExit()) {
//            return true;
//        }
        return false;
    }

    /**
     * 激活脚环引导图
     */
    public void showActivateGuideView(View guideView) {
        mGuideInstance = UserGuideUtil.showActivateGuideView(guideView, R.id.ringItemBtnSet, getActivity(),
                new GuideBuilder.OnVisibilityChangedListener() {
                    @Override
                    public void onShown() {
                    }

                    @Override
                    public void onDismiss() {
                        mGuideInstance = null;
                    }
                });
    }


    /**
     * 提示绑定失败提示框
     *
     * @param ids
     */
    private void showBindingErrorDialog(String ids) {
        MaterialDialog mCreateDialog = new MaterialDialog.Builder(getActivity())
                .title("绑定失败")
                .content(//"被创建的任务将不会包含押解人员、规划路线以及使用车辆。 \n\n" +
                        "脚环：" + ids + "绑定失败，请重新开锁并绑定！")
                .positiveText("确定")
                .positiveColorRes(R.color.back_ground_green)
                //.negativeText(R.string.dialog_negative_text)
                //.negativeColorRes(R.color.dialog_bg)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                    }
                }).build();
        ViewUtil.removeHomeKeyListener(mCreateDialog);
    }


    /**
     * 创建任务弹框
     */
    private void showRingSureDialog() {
        boolean flag = false;
        StringBuilder buffer = new StringBuilder();
        CreateMissionActivity activity = (CreateMissionActivity) getActivity();
        for (FootRingNewEntity entity : activity.getmRingList()) {
            if (entity.isMyBingding()) {
                flag = true;
                buffer.append(entity.getRingID() + ",");
            }
        }
        if (!flag) {
            AppUtil.showLengthToast(getActivity(), "请先激活脚环");
            return;
        }

        final String ids = buffer.substring(0, buffer.length() - 1);
//        final String ids = "35d8,2579,4d85,2d5b";

        MaterialDialog mCreateDialog = new MaterialDialog.Builder(getActivity())
                .title("创建任务")
                .content(//"被创建的任务将不会包含押解人员、规划路线以及使用车辆。 \n\n" +
                        "是否确认要使用脚环：" + ids + " 创建任务？")
                .positiveText("创建")
                .positiveColorRes(R.color.back_ground_green)
                .negativeText(R.string.dialog_negative_text)
                .negativeColorRes(R.color.dialog_bg)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        String result = checkErrorFootring();
                        if (result.equals("")) {
                            CreateMissionActivity activity = (CreateMissionActivity) getContext();
                            activity.IsFinish = true;
                            Log.d("脚环数据：","绑定脚环数量："+ids.split(",").length);
                            SPUtil.putIntValue(SPUtil.FOOT_RING_NUMBER,ids.split(",").length);
                            intentToDeviceTask();
                        } else {
                            showBindingErrorDialog(result);
                        }
                    }
                }).build();
        ViewUtil.removeHomeKeyListener(mCreateDialog);
    }

    /**
     * 创建任务
     */
    private void intentToDeviceTask() {
        //todo 发送命令给脚环完成
        //todo 一对一

        mPresenter.createSimpleTask();

        showLoadDialog("正在创建任务...");
    }


    /**
     * 创建任务成功
     */
    protected void createTaskSuccess(String missId) {
        dismissLoadingDialog();
        AppUtil.showShortToast(getContext(), "任务创建成功");
        Bundle bundle = new Bundle();
        bundle.putString(KeyConstant.MISSION_ID, missId);
        bundle.putString(KeyConstant.MISSION_NAME, mMissionName);
        bundle.putString(KeyConstant.MISSION_TIME, mMissionTime);
        bundle.putString(KeyConstant.MISSION_CAR, mMissionCar);
        CreateMissionActivity activity = (CreateMissionActivity) getActivity();
        activity.openActWithFadeOut(MissionActivity.class, bundle);
    }

    /**
     * 创建任务失败
     */
    protected void createTaskFail(String reason) {
        AppUtil.showShortToast(getContext(), reason);
        dismissLoadingDialog();
        //showRingSureDialog();
    }

    @Override
    public void onDestroyView() {
        if (mRadarScanView != null) {
            mRadarScanView.stopAnimation();
            mRadarScanView.onDestroy();
            mRadarScanView = null;
        }
        if (mRingAdapter != null) {
            mRingAdapter.destroy();
            mRingAdapter = null;
        }
        super.onDestroyView();
    }
}
